package com.heima.comment.interceptor;


import com.heima.comment.util.AppThreadLocalUtil;
import com.heima.model.user.entity.ApUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    /**
     * 前置拦截 -  获取请求头中的  userId , 放入到当前线程中
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId) && !StringUtils.equals("0", userId)) {
            //2. 存入线程
            ApUser apUser = new ApUser();
            apUser.setId(Long.valueOf(userId));

            AppThreadLocalUtil.setUser(apUser);
        }

        return super.preHandle(request, response, handler);
    }

    /**
     * 清楚线程中的用户数据
     *
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清楚线程数据
        AppThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}